package com.hk.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ArithmeticVerifyCodeUtils {
    // 生成随机算术表达式并计算结果
    public static ArithmeticInfo generateArithmetic() {
        Random random = new Random();
        int num1 = random.nextInt(10) + 1; // 1-10
        int num2 = random.nextInt(10) + 1; // 1-10
        int operator = random.nextInt(2);  // 0:加法, 1:减法
        
        String expression;
        int result;
        
        if (operator == 0) {
            expression = num1 + " + " + num2 + " = ?";
            result = num1 + num2;
        } else {
            // 确保减法结果为正数
            if (num1 < num2) {
                int temp = num1;
                num1 = num2;
                num2 = temp;
            }
            expression = num1 + " - " + num2 + " = ?";
            result = num1 - num2;
        }
        
        return new ArithmeticInfo(expression, result);
    }

    // 生成验证码图片
    public static BufferedImage createImage(String expression) {
        int width = 120, height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景和干扰元素（与之前类似）
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, width - 1, height - 1);
        
        // 添加随机干扰点和线
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            g.fillRect(x, y, 1, 1);
        }
        
        // 绘制算术表达式
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString(expression, 20, 28);
        
        g.dispose();
        return image;
    }

    // 内部类：存储算术表达式和结果
    public static class ArithmeticInfo {
        private String expression;
        private int result;

        public ArithmeticInfo(String expression, int result) {
            this.expression = expression;
            this.result = result;
        }

        public String getExpression() { return expression; }
        public int getResult() { return result; }
    }
}